import 'package:erp/Entity/SupplierType.dart';
import 'package:erp/Events/EventAddrs.dart';
import 'package:erp/Store/SupplierStore.dart';
import 'package:erp/UI/Components/CustomizedScaffold.dart';
import 'package:erp/UI/Components/EventfulState.dart';
import 'package:erp/UI/Components/ListDividerGenerator.dart';
import 'package:erp/UI/Components/LogoScaffold.dart';
import 'package:erp/UI/Components/MessageDialog.dart';
import 'package:erp/UI/Components/QuestionDialog.dart';
import 'package:erp/global.dart';
import 'package:flutter/material.dart';

class SupplierTypePage extends StatelessWidget {
  bool selectionMode;
  SupplierTypePage({this.selectionMode = false});
  @override
  Widget build(BuildContext context) => SupplierTypePageStateful(selectionMode);
}

class SupplierTypePageStateful extends StatefulWidget {
  bool selectMode;
  SupplierTypePageStateful(this.selectMode);
  @override
  State<StatefulWidget> createState() => SupplierTypePageState();
}

class SupplierTypePageState extends EventfulState<SupplierTypePageStateful> {

  @override
  void initState() {
    eventIds = [
      globalBus.subscribe(Events.SUPPLIER_TYPE_INSERT_SUCCESS, (bus, data){setState(() {});}),
      globalBus.subscribe(Events.SUPPLIER_TYPE_SELECT_SUCCESS, (bus, data){setState(() {});}),
      globalBus.subscribe(Events.SUPPLIER_TYPE_UPDATE_SUCCESS, (bus, data){setState(() {});}),
      globalBus.subscribe(Events.SUPPLIER_TYPE_DELETE_SUCCESS, (bus, data){setState(() {});}),
      globalBus.subscribe(Events.SUPPLIER_TYPE_INSERT_ERROR, (bus, error){
        showMessageDialog(context, title: "قوشۇش مەغلۇپ بولدى", content: error.toString());
      }),
      globalBus.subscribe(Events.SUPPLIER_TYPE_UPDATE_ERROR, (bus, error){
        showMessageDialog(context, title: "يىڭىلاش مەغلۇپ بولدى", content: error.toString());
      }),
      globalBus.subscribe(Events.SUPPLIER_TYPE_DELETE_ERROR, (bus, error){
        showMessageDialog(context, title: "ئۆچۈرۈش مەغلۇپ بولدى", content: error.toString());
      })
    ];
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return LogoScaffold(
      assetsLogoName: "assets/pictures/purchases.png",
      title: "مال تەمىنلىگۈچى تۈرى",
      heroName: "SupplierTypeHero",
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () async {
          var data = SupplierType();
          var result = await showSupplierTypeEditor(context, data);
          if (result){
            globalBus.publish(Events.SUPPLIER_TYPE_INSERT_REQUEST, data);
          }
        },
      ),
      contentDelegate: SliverChildListDelegate(ListDividerGenerator(SupplierStore.supplierTypes.map((item) => buildItem(context, item)).toList(), Divider()).items),
    );
  }

  Widget buildItem(BuildContext context, SupplierType data){
    return ListTile(
      leading: Image.asset("assets/pictures/purchases.png", width: 40.0, height: 40.0,),
      title: Text(data.name),
      subtitle: Text(data.memo),
      trailing: Wrap(
        direction: Axis.horizontal,
          children: <Widget>[
            IconButton(icon: Icon(Icons.edit), onPressed: () async {
              var cloned = data.clone();
              var result = await showSupplierTypeEditor(context, cloned) ?? false;
              if (result){
                globalBus.publish(Events.SUPPLIER_TYPE_UPDATE_REQUEST, cloned);
              }
            }),
            IconButton(icon: Icon(Icons.delete), onPressed: () async {
              var result = await showQuestionDialog(context, title: "ئەسكەرتىش", content: "راستىنلا ئۆچۈرۋىتەمسىز؟") ?? false;
              if (result) globalBus.publish(Events.SUPPLIER_TYPE_DELETE_REQUEST, data);
            })
          ],
      ),
      onTap: (){
        if (widget.selectMode){
          Navigator.of(context).pop(data);
        }
      },
    );
  }

  Future<bool> showSupplierTypeEditor(BuildContext context, SupplierType data) async {
    var nameEditingController = TextEditingController(text: data.name ?? "");
    var descriptionEditingController = TextEditingController(text: data.memo ?? "");
    var dialog = AlertDialog(
      title: Text("مال تەمىنلىگۈچى تۈرى ئۇچۇرلىرىنى كىرگۈزۈڭ"),
      content: Wrap(
        direction: Axis.horizontal,
        children: <Widget>[
          TextField(
            controller: nameEditingController,
            textAlign: TextAlign.start,
            decoration: InputDecoration(
              hintText: "ئىسمىنى كىرگۈزۈڭ",
              labelText: "ئىسمى"
            ),
            onChanged: (text) => data.name = text,
          ),
          TextField(
            controller: descriptionEditingController,
            textAlign: TextAlign.start,
            decoration: InputDecoration(
              hintText: "چۈشەندۈرۈلىشىنى كىرگۈزۈڭ",
              labelText: "چۈشەندۈرۈلىشى"
            ),
            onChanged: (text) => data.memo = text,
          )
        ],
      ),
      actions: <Widget>[
        FlatButton(child: Text("بىكار قىلىش"), onPressed: (){
          Navigator.of(context).pop(false);
        }),
        FlatButton(child: Text("جەزىملەشتۈرۈش"), onPressed: (){
          Navigator.of(context).pop(true);
        })
      ],
    );

    return showDialog(context: context, barrierDismissible: false, builder: (context) => dialog);
  }
}